<?php

namespace JsonRpc\Services\System;

use JsonRpc\Models\SysPeriod;
use JsonRpc\Services\CommonService;

/**
 *  用户
 * @author walkor <worker-man@qq.com>
 */
class PeriodService
{
    use CommonService;

    private static function getBaseModel()
    {
        return "JsonRpc\\Models\\SysPeriod";
    }

    public static function ping()
    {
        return 'OK';
    }

    static function saveData($params)
    {
        if (isset($params['id']) && $params['id']) {
            //更新
            $model = SysPeriod::find($params['id']);
            $model->updated_by = $params['curr_user_id'];

        } else {
            //新增
            $user = UserService::getInfoById(['id' => $params['curr_user_id']]);
            unset($params['id']);
            $model = new SysPeriod();
            $model->client_id = 1;
            $model->org_id = 1;
            $model->created_by = $user['id'];
            $model->updated_by = $user['id'];
            $model->name = substr($params['startdate'], 0, 7);
        }
        if (count(SysPeriod::where('enddate', '>', $params['startdate'])->get()) !== 0) {
            throw new \Exception('此时间段内已存在期间');
        }

        $model->is_active = $params['is_active'];
        $model->startdate = $params['startdate'];
        $model->enddate = $params['enddate'];
        $model->is_open = $params['is_open'];
        return $model->save();
    }

    /**
     * 打开或关闭
     * @param $params
     * @return mixed
     */
    static function openOrClose($params)
    {
        //更新
        $model = SysPeriod::find($params['id']);
        $model->updated_by = $params['curr_user_id'];
        $model->is_open = $params['is_open'];
        return $model->save();
    }
}
